<script lang="ts">
	import { RESOURCE_TYPE, type ResourceInfo } from '$lib/api/proto/resource_api';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import { EllipsisVertical, Search } from 'lucide-svelte';
	import EditResourceModal from './EditResourceModal.svelte';
	import SimpleEditor from '$lib/components/editor/SimpleEditor.svelte';
	import { goto } from '$app/navigation';
	import ConfirmModal from '$lib/components/modal/ConfirmModal.svelte';

	const PAGE_SIZE = 12;

	let showCreateModal = $state(false);

	let curPage = $state(0);
	let filterResourceType: RESOURCE_TYPE | null = $state(null);
	let tmpKeyword = $state('');
	let keyword = $state('');
	let resourceList: ResourceInfo[] = $state([]);
	let totalCount = $state(0);
	let updateResourceInfo: ResourceInfo | null = $state(null);
	let removeResourceInfo: ResourceInfo | null = $state(null);

	const pageCount = $derived(Math.ceil((totalCount ?? 0) / PAGE_SIZE));

	async function loadResourceList() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.resourceApiClient.list({
				sessionId: userStore.userSession,
				filterByResourceType: filterResourceType != null,
				resourceType: filterResourceType ?? RESOURCE_TYPE.RESOURCE_TYPE_CARD,
				filterByKeyword: keyword.trim() != '',
				keyword: keyword.trim(),
				offset: curPage * PAGE_SIZE,
				limit: PAGE_SIZE
			}).response
		);
		totalCount = res.totalCount;
		resourceList = res.resourceList;
	}

	async function onUpdateResource(resourceId: string) {
		if (userStore.userInfo == null || userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.resourceApiClient.get({
				sessionId: userStore.userSession,
				resourceId: resourceId
			}).response
		);
		const tmpList = resourceList.slice();
		const index = tmpList.findIndex((item) => item.resourceId == resourceId);
		if (index != -1 && res.resource != undefined) {
			tmpList[index] = res.resource;
			resourceList = tmpList;
		}
	}

	async function removeResource() {
		if (removeResourceInfo == null || userStore.userSession == null) {
			return;
		}
		await callApi(
			appStore.resourceApiClient.remove({
				sessionId: userStore.userSession,
				resourceId: removeResourceInfo.resourceId
			}).response
		);
		await loadResourceList();
		removeResourceInfo = null;
		appStore.addToastMessage({
			level: 'success',
			content: '删除资源成功',
			keepTime: 2000
		});
	}

	$effect(() => {
		loadResourceList();
	});

	$effect(() => {
		if (tmpKeyword == '') {
			keyword = '';
		}
	});
</script>

<div class="pl-[100px] pr-[100px] pt-[10px] mt-[20px]">
	<div class="flex justify-between border-b-2 border-base-200 h-[50px]">
		<h3 class="text-3xl">我的资料库</h3>
		<div class="flex items-center gap-4">
			<label class="input w-[180px]">
				<input
					type="search"
					class="input"
					placeholder="过滤标题"
					bind:value={tmpKeyword}
					onkeypress={(e) => {
						if (e.key === 'Enter') {
							keyword = tmpKeyword;
						} else if (e.key == 'Esc') {
							tmpKeyword = '';
						}
					}}
				/>
				<button type="button" class="btn btn-ghost p-1" onclick={() => (keyword = tmpKeyword)}
					><Search /></button
				>
			</label>
			<select class="select w-[180px]" bind:value={filterResourceType}>
				<option value={null}>全部</option>
				<option value={RESOURCE_TYPE.RESOURCE_TYPE_CARD}>知识卡片</option>
				<option value={RESOURCE_TYPE.RESOURCE_TYPE_EXAM}>试题</option>
			</select>
			<button class="btn btn-primary" onclick={() => (showCreateModal = true)}>创建</button>
		</div>
	</div>
	<div class="flex flex-wrap gap-2 p-2">
		{#each resourceList as resource}
			<div class="card bg-base-300 w-[300px] h-[220px] shadow-sm">
				<div class="card-body">
					<div class="flex w-[260px] justify-between items-center">
						<h2
							class="card-title text-secondary max-w-[200px] overflow-hidden truncate"
							title={resource.basicInfo?.name}
						>
							{#if resource.resourceType == RESOURCE_TYPE.RESOURCE_TYPE_CARD}
								知识卡片
							{:else if resource.resourceType == RESOURCE_TYPE.RESOURCE_TYPE_EXAM}
								试题
							{/if}
							:{resource.basicInfo?.name}
						</h2>

						<div class="dropdown">
							<div tabindex="0" role="button" class="btn btn-ghost">
								<EllipsisVertical size={16} />
							</div>
							<ul
								class="menu dropdown-content bg-base-100 rounded-box z-1 w-[80px] p-2 shadow-sm gap-2"
							>
								<li>
									<button
										type="button"
										class="btn btn-ghost"
										onclick={() => (updateResourceInfo = resource)}>修改</button
									>
								</li>
								<li class="text-error">
									<button
										type="button"
										class="btn btn-ghost"
										onclick={() => (removeResourceInfo = resource)}>删除</button
									>
								</li>
							</ul>
						</div>
					</div>

					<SimpleEditor data={resource.basicInfo?.desc} sizeClass="h-[80px]" readOnly />
					<div class="card-actions justify-end">
						<button
							class="btn btn-secondary"
							onclick={() => {
								if (resource.resourceType == RESOURCE_TYPE.RESOURCE_TYPE_CARD) {
									goto(`/app/resource/card?resourceId=${resource.resourceId}`);
								} else if (resource.resourceType == RESOURCE_TYPE.RESOURCE_TYPE_EXAM) {
									goto(`/app/resource/exam?resourceId=${resource.resourceId}`);
								}
							}}>打开</button
						>
					</div>
				</div>
			</div>
		{/each}
	</div>

	{#if pageCount > 1}
		<div class="flex justify-center mt-[20px]">
			<div class="join bg-base-200">
				{#if curPage > 0}
					<button class="join-item btn btn-lg" onclick={() => (curPage = curPage - 1)}
						>上一页</button
					>
				{/if}
				{#if curPage != 0}
					<button
						class="join-item btn btn-lg {curPage == 0 ? 'btn-active' : ''}"
						onclick={() => (curPage = 0)}>1</button
					>
				{/if}
				{#if pageCount > 3 && curPage > 1}
					<button class="join-item btn btn-lg btn-disabled">...</button>
				{/if}
				{#if curPage < pageCount}
					<button class="join-item btn btn-lg btn-active">{curPage + 1}</button>
				{/if}
				{#if curPage + 1 < pageCount}
					<button class="join-item btn btn-lg" onclick={() => (curPage += 1)}>{curPage + 2}</button>
				{/if}
				{#if pageCount - curPage > 4}
					<button class="join-item btn btn-lg btn-disabled">...</button>
				{/if}
				{#if pageCount - curPage > 3}
					<button class="join-item btn btn-lg" onclick={() => (curPage = pageCount - 2)}
						>{pageCount - 1}</button
					>
				{/if}
				{#if pageCount - curPage > 2}
					<button class="join-item btn btn-lg" onclick={() => (curPage = pageCount - 1)}
						>{pageCount}</button
					>
				{/if}
				{#if curPage + 1 < pageCount}
					<button class="join-item btn btn-lg" onclick={() => (curPage = curPage + 1)}
						>下一页</button
					>
				{/if}
			</div>
		</div>
	{/if}
</div>

<div class="absolute -left-[10000px]">
	{#if showCreateModal}
		<EditResourceModal
			onCancel={() => (showCreateModal = false)}
			onOk={() => {
				showCreateModal = false;
				if (filterResourceType == null && curPage == 0) {
					loadResourceList();
				} else {
					filterResourceType = null;
					curPage = 0;
				}
			}}
		/>
	{/if}
	{#if updateResourceInfo != null}
		<EditResourceModal
			resourceInfo={updateResourceInfo}
			onCancel={() => (updateResourceInfo = null)}
			onOk={() => {
				onUpdateResource(updateResourceInfo?.resourceId ?? '');
				updateResourceInfo = null;
			}}
		/>
	{/if}
	{#if removeResourceInfo != null}
		<ConfirmModal
			title="删除资料"
			content={`是否删除资料${removeResourceInfo.basicInfo?.name}?`}
			type="error"
			okName="删除"
			onCancel={() => (removeResourceInfo = null)}
			onOk={() => removeResource()}
		/>
	{/if}
</div>
